package com.sap.sap_mangers.until;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 樊东升
 * @date 2022/8/5 11:28
 */
@Component
public class CosUntil {
    private final static String SECRET_ID = "AKIDQebJkxve6G9m8DgwykGXZMtCG4cuxlJd";
    private final static String SECRET_KEY = "6yaw2uXv5ze3C5j7HCsITO4VhdJlxtb4";
    /**
     * bucket名需包含appid
     */
    private final static String BUCKET_NAME = "sap-1256773093";
    /**
     * 地域
     */
    private final static String BUCKET_REGION = "cos.ap-nanjing";
    /**
     * 网址
     */
    private final static String COS_URL = "https://sap-1256773093.cos.ap-nanjing.myqcloud.com/";

    public String getCosUrl(MultipartFile file, String cosKey) throws IOException {
        // 创建cos客户端
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        Region region = new Region(BUCKET_REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 获取输入流
        InputStream inputStream = new BufferedInputStream(file.getInputStream());
        ObjectMetadata objectMetadata = new ObjectMetadata();

        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, cosKey, inputStream, objectMetadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        // 完成上传之后，关闭连接
        cosClient.shutdown();
        // 通过回调函数判断是否上传成功，有etag信息则表示上传成功，否则上传失败
        if (putObjectResult.getETag() == null) {
            throw new RuntimeException("上传失败【未知】");
        }

        return "https://sap-1256773093.cos.ap-nanjing.myqcloud.com/" + cosKey;
    }

    /**
     * 删除对象储存里的图片
     *
     * @param url 图片的完整URL
     */
    public void deleteCosUrl(String url) {
        // 创建cos客户端
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        Region region = new Region(BUCKET_REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);
        // 指定被删除的文件在 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示删除位于 folder 路径下的文件 picture.jpg
        String[] urls = url.split(COS_URL);
        cosClient.deleteObject(BUCKET_NAME, urls[1]);
    }
}
